package it.unipg.bipod.web;

import it.unipg.bipod.applicationLogic.*;
import it.unipg.bipod.dataModel.*;

import javax.faces.bean.*;

import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Comparator;

@ManagedBean(name="segretarioBandi")
@ViewScoped
public class SegretarioBandiBean {
	@ManagedProperty(value="#{segretario.application}")
	private SegretarioApplication application;
	private ListManager<BandoBean> bandiBean;
	private static final int PAGE_SIZE = 20;
	
	public SegretarioBandiBean() {
		this.application = null;
		this.bandiBean = null;
	}

	public void setApplication(SegretarioApplication application) {
		this.application = application;
	}

	public SegretarioApplication getApplication() {
		return application;
	}
	
	public ListManager<BandoBean> getBandi() {
		if (this.bandiBean == null) {
			try {
				// Estrazione e ordinamento
				Bando[] bandi = application.getBandi();
				
				Arrays.sort(bandi, new Comparator<Bando>() {
					public int compare(Bando b1, Bando b2) {
						return b2.getDataPubblicazione().compareTo(b1.getDataPubblicazione());
					}
				});
				
				// Incapsulamento
				BandoBean[] bandiBean = new BandoBean[bandi.length];				
				for (int i = 0; i < bandi.length; ++i)
					bandiBean[i] = new BandoBean(bandi[i]);
				
				this.bandiBean = new ListManager<BandoBean>(bandiBean, PAGE_SIZE);
				return this.bandiBean;
			} catch (ApplicationException e) {
				return null;
			}
		} else {
			return this.bandiBean;
		}
	}
	
	public boolean getBandiPresenti() {
		if (bandiBean != null)
			return bandiBean.getSize() > 0;
		else {
			getBandi();
			return bandiBean.getSize() > 0;
		}
	}
	
	public class BandoBean {
		private Bando bando;
		
		public BandoBean(Bando bando) {
			this.bando = bando;
		}
		
		public String getDataPubblicazione() {
			Format dateFormat = new SimpleDateFormat("dd/MM/yyyy");
			return dateFormat.format(bando.getDataPubblicazione());
		}
		
		public String getDataScadenza() {
			Format dateFormat = new SimpleDateFormat("dd/MM/yyyy");
			return dateFormat.format(bando.getDataScadenza());
		}
		
		public boolean getAttivo() {
			java.sql.Timestamp now = new java.sql.Timestamp(System.currentTimeMillis());
			return now.after(bando.getDataPubblicazione()) && now.before(bando.getDataScadenza());
		}
		
		public int getIdBando() {
			return bando.getIdBando();
		}
	}

}
